package com.aode.musicplay;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.aode.common.bean.response.Music;

public class MusicPlayActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection,SeekBar.OnSeekBarChangeListener{
    private ImageView iv_disk;//光盘（设置动画）
    private static SeekBar musicProgressBar;//进度条
    private static TextView currentTv;//当前音乐播放时长
    private static TextView totalTv;//当前音乐总时长
    private Button btn_play,btn_pause,btn_continue,btn_exit;//四个控制按钮
    private ObjectAnimator animator;
    private Music music;
    private MusicPlayerService.MusicControl control;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_musicplay);
        init();
    }
    private void init(){
        iv_disk = findViewById(R.id.iv_music);
        musicProgressBar = findViewById(R.id.sb);
        currentTv = findViewById(R.id.tv_progress);
        totalTv = findViewById(R.id.tv_total);
        btn_play = findViewById(R.id.btn_play);
        btn_continue = findViewById(R.id.btn_continue_play);
        btn_pause = findViewById(R.id.btn_pause);
        btn_exit = findViewById(R.id.btn_exit);


        btn_play.setOnClickListener(this);
        btn_pause.setOnClickListener(this);
        btn_play.setOnClickListener(this);
        btn_exit.setOnClickListener(this);
        btn_continue.setOnClickListener(this);

        animator = ObjectAnimator.ofFloat(iv_disk,"rotation",0,360.0F);
        animator.setDuration(10000);//设置动画的时长，单位为毫秒，这里设置了10秒一圈
        animator.setInterpolator(new LinearInterpolator());//旋转时间函数为线性，意为匀速旋转
        animator.setRepeatCount(-1);//设置转动圈数，-1为一直转动。


        Intent intent = new Intent(getApplicationContext(),MusicPlayerService.class);
        bindService(intent,this,BIND_AUTO_CREATE);
        music = (Music) getIntent().getParcelableExtra("music");
        Log.e("TAG",music.getMusicProduct());
        if(control!=null){
            control.setUrl(music.getMusicProduct());
        }
        musicProgressBar.setOnSeekBarChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btn_play) {//播放音乐
            if (control != null) {
                control.play();
                //光盘开始转动
                animator.start();
            }
        } else if (id == R.id.btn_pause) {//暂停音乐
            if (control != null) {
                control.pause();
                //光盘暂停
                animator.pause();
            }
        } else if (id == R.id.btn_continue_play) {//继续播放
            if (control != null) {
                control.resume();
                //光盘继续播放
                animator.resume();
            } else {
                Toast.makeText(MusicPlayActivity.this, "请先播放音乐", Toast.LENGTH_SHORT);
            }
        } else if (id == R.id.btn_exit) {//退出应用
            finish();
        }
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        control = (MusicPlayerService.MusicControl)service;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        //当音乐停止后，停止光盘动画
        Log.e("TAG",seekBar.getMax()+"");
        Log.e("TAG",progress+"");
        if(progress == seekBar.getMax()){

            animator.pause();
        }
        if(fromUser){//判断是不是用户移动的
            if(control!=null){
                control.seekTo(progress);
            }

        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        if(control!=null){
            control.pause();
        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if(control!=null){
            try {
                control.resume();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    @Override
    protected void onDestroy() {
        if(control!=null){
            control.stop();
            unbindService(this);
        }
        super.onDestroy();
    }
    //获取从MusicPlayerServices传递过来的消息
    public static Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();//获取从子线程发送过来的音乐播放进度
            int duration = bundle.getInt("duration");//歌曲总时长
            int currentPosition = bundle.getInt("currentPosition");//歌曲当前进度
            musicProgressBar.setMax(duration);
            musicProgressBar.setProgress(currentPosition);
            String  totalTime = msToMinSec(duration);
            String currentTime = msToMinSec(currentPosition);
            totalTv.setText(totalTime);
            currentTv.setText(currentTime);
        }
    };

    private static String msToMinSec(int ms) {
        int sec = ms / 1000;
        int min = sec / 60;
        sec -= min * 60;
        return String.format("%02d:%02d",min,sec);
    }
}
